package net.tv90.volunteerserveradmin.service;

import jakarta.annotation.Resource;
import net.tv90.volunteerserveradmin.dao.ImageRepository;
import net.tv90.volunteerserveradmin.exception.ServiceException;
import net.tv90.volunteerserveradmin.model.domain.Image;
import net.tv90.volunteerserveradmin.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.util.unit.DataSize;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

@Service
public class ImageService {

    @Resource
    private ImageRepository imageRepository;

    private final Path rootLoc = Paths.get("assets/images");

    private final String[] suffix = {"jpe", "jpg", "jpeg", "gif", "png", "bmp", "ico", "svg", "svgz", "tif", "tiff", "webp"};

    @Value("${spring.servlet.multipart.max-file-size}")
    private String fileMaxSize;

    public List<Image> getAllImages() {
        return imageRepository.findAll();
    }

    public Image getImageById(Long id) {
        if (id == null) {
            return new Image();
        }
        return imageRepository.findById(id).orElseThrow(() -> new ServiceException("图片id不存在"));
    }

    public String getImagePathById(Long id) {
        if (id == null) {
            return "";
        }
        Image img = imageRepository.findById(id).orElseThrow(() -> new ServiceException("图片id不存在"));
        return img.getUrl();
    }

    @Transactional(rollbackFor = Exception.class)
    public Image uploadImage(MultipartFile file) {
        try {
            if (file == null || file.getOriginalFilename() == null || file.isEmpty()) {
                throw new ServiceException("文件不能为空");
            }

            String oriName = file.getOriginalFilename();
            String ext = StringUtils.getFilenameExtension(oriName);

            boolean isLegal = false;
            for (String s : suffix) {
                if (s.equalsIgnoreCase(ext)) {
                    isLegal = true;
                    break;
                }
            }
            if (!isLegal) {
                throw new ServiceException("文件格式不合法");
            }
            if (file.getSize() > DataSize.parse(fileMaxSize).toBytes()) {
                throw new ServiceException("文件过大");
            }

            LocalDateTime now = LocalDateTime.now();

            String datePrefix = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String url = datePrefix + "/" + UUID.randomUUID() + "." + ext;

            Image image = new Image();
            image.setName(oriName);
            image.setUrl("/images/" + url);
            image.setSize(file.getSize());
            image.setUploadTime(now);
            image.setMd5(MD5Utils.calculateMD5(file));

            // 保存到本地
            try {
                Files.createDirectories(rootLoc.resolve(datePrefix));
                file.transferTo(rootLoc.resolve(url));
            } catch (IOException e) {
                Files.createDirectories(rootLoc);
                throw new ServiceException("服务器内部错误，请联系管理员");
            }

            // 保存到数据库
            imageRepository.save(image);
            return image;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}